package noidunggopy.backing;

import common.Utils;

import java.io.File;

import java.util.List;

import java.io.FileOutputStream;
import java.io.InputStream;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;

import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.WindowState;

import javax.servlet.http.HttpServletRequest;

import nl.captcha.Captcha;

import noidunggopy.noidunggopy;

import noidunggopy.resource.noidunggopyBundle;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;

import oracle.adf.view.rich.component.rich.output.RichOutputText;

import org.apache.myfaces.trinidad.model.UploadedFile;

import util.MailImplement;

public class noidunggopyBacking {
    private String answer;
    private RichPanelFormLayout formlayout;
    private UploadedFile _file;
    private String tieudendgopy;
    private static String emailnhan;
    private String ketqua = "";

    private RichOutputText rotKetqua =  new RichOutputText();
    private RichInputText txtHoten = new RichInputText();
    private RichInputText txtEmailnguoigui = new RichInputText();
    private RichInputText txtTieude = new RichInputText();
    private RichInputText txtNoidung = new RichInputText();
    //LABEL VS MESSAGE
    private String hotenLabel;
    private String hotenInvalid;
    private String diachiLabel;
    private String phoneLabel;
    private String phoneInvalid;
    private String emailRequired;
    private String emailInvalid;
    private String tieudeLabel;
    private String tieudeInvalid;
    private String chudeLabel;
    private String chudeInvalid;
    private String fileLabel;
    private String noidungLabel;
    private String noidungInvalid;
    private String doimaLabel;
    private String guiLabel;
    
    public noidunggopyBacking(){
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            ketqua = "";
            rotKetqua.setVisible(false);
        }
    }

    /**
     * Author       Date        Comment
     *  TớiNT    24/09/2012     Thêm mới
     * @return
     */
    public void beforePhase(PhaseEvent phaseEvent) {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        Integer reset =
            (Integer)request.getPortletSession().getAttribute("reset");
        if (reset != null && reset == 1) {
            request.getPortletSession().setAttribute("reset", 0);
            Utils.execute("Rollback");
            Utils.execute("CreateInsert");
        }
    }

    /**
     * Author       Date        Comment
     *  TớiNT    09/11/2012     Thêm mới hỏi đáp
     * @return
     */
    public void Insert(ActionEvent actionEvent) {
        if (capcha()) {
            try {
                boolean fileupload = true;
                File filePath =
                    new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                             Utils.ENUM_CAU_HINH_KHOA.DTVB_DIR.getValue("HtCauHinhView1Iterator"));
                File duongdantuongdoi =
                    new File(Utils.ENUM_CAU_HINH_KHOA.DTVB_DIR.getValue("HtCauHinhView1Iterator"));
                DCIteratorBinding NdgopyIterrator =
                    Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator");
                NdgopyIterrator.getCurrentRow().setAttribute("NgayGui",
                                                             Utils.getCurrentDate().dateValue().toString());
                DCIteratorBinding DsvanbanIterrator =
                    Utils.getIteratorBinding("DtvbDsVanbanGopyView1Iterator");
                String Iddsvanban =
                    DsvanbanIterrator.getCurrentRow().getAttribute("Id").toString();
                NdgopyIterrator.getCurrentRow().setAttribute("NoidungvanbanId",
                                                             Iddsvanban);
                //File filePath = new File("C:\\DTVB\\");
                UploadedFile file = this.getFile();
                File obj = null;
                FileOutputStream output = null;

                Object fileId = null;
                DCIteratorBinding fileIterator1 =
                    Utils.getIteratorBinding("HtFileView1Iterator");
                if (file != null) {
                    String fileName = file.getFilename();
                    if (Utils.checkDefaultFileExtension(fileName)) {
                        try {
                            if (filePath.exists() == false) {
                                filePath.mkdirs();
                            }
                            byte buffer[] = new byte[1024];
                            int size = 0;
                            InputStream input = file.getInputStream();
                            Utils.execute("HtFileInsert");
                            fileId =
                                    fileIterator1.getCurrentRow().getAttribute("Id");

                            output =
                                    new FileOutputStream(new File(filePath, fileId +
                                                                  "_" +
                                                                  fileName));
                            while ((size = input.read(buffer)) != -1) {
                                output.write(buffer);
                            }
                            obj = new File(filePath, fileId + "_" + fileName);
                            Utils.processUpload(file, duongdantuongdoi,
                                                "HtFileView1Iterator",
                                                "DtvbNoidunggopyView1Iterator",
                                                Utils.ENUM_MA_UNG_DUNG.DTVB,
                                                fileId.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (output != null) {
                                try {
                                    output.flush();
                                    output.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        this.setFile(null);
                        this.setAnswer(null);
                        ketqua = "Hệ thống hỗ trợ file có định dạng: *.doc,*.docx,*.xls,*.xlsx,<br/>*.ppt,*.pptx,*.odt,*.ods,*.odp,*.pdf,*.zip,*.rar,*.txt";
                        rotKetqua.setInlineStyle("color:red;");
                        rotKetqua.setVisible(true);
                        PortletRequest request =
                            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
                        request.getPortletSession().setAttribute("unreset", 2);
                        fileupload = false;
                    }
                }
                if (fileupload) {
                    // goi ham gui mail
                    Send(obj);
                    List lst = Utils.execute("Commit");
                    if (lst == null) {
                        this.setFile(null);
                        this.setAnswer(null);
                        Utils.iteratorRefresh("DtvbNoidunggopyView1Iterator");
                        Utils.execute("CreateInsert");
                        ketqua = "Gửi góp ý dự thảo văn bản thành công.";
                        rotKetqua.setInlineStyle("color:blue;");
                        rotKetqua.setVisible(true);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            if (this.getAnswer() != null) {
                ketqua = "Bạn nhập sai mã xác nhận. Yêu cầu nhập lại.";
                rotKetqua.setInlineStyle("color:red;");
                rotKetqua.setVisible(true);
                this.setAnswer(null);
                this.setFile(null);
            } else {
                ketqua = "Yêu cầu nhập mã xác nhận.";
                rotKetqua.setInlineStyle("color:red;");
                rotKetqua.setVisible(true);
                this.setFile(null);
            }
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            request.getPortletSession().setAttribute("unreset", 2);
        }
    }

    /**
     * Author       Date        Comment
     *  TớiNT    09/11/2012     Kiểm tra captcha
     * @return
     */
    public boolean capcha() {
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpServletRequest httpServletRequest =
                (HttpServletRequest)request.getAttribute("javax.servlet.request");
            if (httpServletRequest != null) {
                Captcha captcha =
                    (Captcha)httpServletRequest.getSession().getAttribute(Captcha.NAME);
                if (captcha != null && this.getAnswer() != null) {
                    if (captcha.isCorrect(this.getAnswer())) {
                        return true;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    private String TieudeNoidunggopy() {
        String tieudeNdgopy = "Nội dung góp ý";
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            if (request.getParameter("tieudendgopy") != null)
                tieudeNdgopy = request.getParameter("tieudendgopy").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return tieudeNdgopy;
    }

    public void Send(File file) {
        MailImplement mail = new MailImplement();
        String tieudemail = txtTieude.getValue().toString();
        String mailnguoigui = txtEmailnguoigui.getValue().toString();
        String noidungmail = txtNoidung.getValue().toString();
        String emailnhan1 = emailnhan;

        try {
            mail.sendEmail(emailnhan1, tieudemail, noidungmail, mailnguoigui,
                           file);
        } catch (Exception mse) {
            mse.printStackTrace();
        }
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getAnswer() {
        return answer;
    }

    public void setFormlayout(RichPanelFormLayout formlayout) {
        this.formlayout = formlayout;
    }

    public RichPanelFormLayout getFormlayout() {
        return formlayout;
    }

    public void setFile(UploadedFile _file) {
        this._file = _file;
    }

    public UploadedFile getFile() {
        return _file;
    }

    public void setTieudendgopy(String tieudendgopy) {
        this.tieudendgopy = tieudendgopy;
    }

    public String getTieudendgopy() {
        tieudendgopy = TieudeNoidunggopy();
        return tieudendgopy;
    }

    public void setTxtHoten(RichInputText txtHoten) {
        this.txtHoten = txtHoten;
    }

    public RichInputText getTxtHoten() {
        return txtHoten;
    }

    public void setTxtEmailnguoigui(RichInputText txtEmailnguoigui) {
        this.txtEmailnguoigui = txtEmailnguoigui;
    }

    public RichInputText getTxtEmailnguoigui() {
        return txtEmailnguoigui;
    }

    public void setTxtTieude(RichInputText txtTieude) {
        this.txtTieude = txtTieude;
    }

    public RichInputText getTxtTieude() {
        return txtTieude;
    }

    public void setTxtNoidung(RichInputText txtNoidung) {
        this.txtNoidung = txtNoidung;
    }

    public RichInputText getTxtNoidung() {
        return txtNoidung;
    }

    public void setEmailnhan(String emailnhan) {
        this.emailnhan = emailnhan;
    }

    public String getEmailnhan() {
        emailnhan = "tanbd@tinhvan.com";
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            if (request.getParameter("emailnoinhan") != null)
                emailnhan = request.getParameter("emailnoinhan").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return emailnhan;
    }

    public void setKetqua(String ketqua) {
        this.ketqua = ketqua;
    }

    public String getKetqua() {
        return ketqua;
    }

    public void setRotKetqua(RichOutputText rotKetqua) {
        this.rotKetqua = rotKetqua;
    }

    public RichOutputText getRotKetqua() {
        return rotKetqua;
    }

    public String getHotenLabel() {
        hotenLabel = Utils.getResource("HO_TEN");
        return hotenLabel;
    }

    public String getHotenInvalid() {
        hotenInvalid = Utils.getResource("HO_TEN_INVALID");
        return hotenInvalid;
    }

    public String getEmailRequired() {
        emailRequired = Utils.getResource("EMAIL_REQUIRED");
        return emailRequired;
    }

    public String getEmailInvalid() {
        emailInvalid = Utils.getResource("EMAIL_INVALID");
        return emailInvalid;
    }

    public String getTieudeLabel() {
        tieudeLabel = Utils.getResource("TIEU_DE");
        return tieudeLabel;
    }

    public String getTieudeInvalid() {
        tieudeInvalid = Utils.getResource("TIEU_DE_INVALID");
        return tieudeInvalid;
    }

    public String getChudeLabel() {
        chudeLabel = Utils.getResource("CHU_DE");
        return chudeLabel;
    }

    public String getChudeInvalid() {
        chudeInvalid = Utils.getResource("CHU_DE_INVALID");
        return chudeInvalid;
    }

    public String getFileLabel() {
        fileLabel = Utils.getResource("FILE_DINH_KEM");
        return fileLabel;
    }

    public String getNoidungLabel() {
        noidungLabel = Utils.getResource("NOI_DUNG_GOP_Y");
        return noidungLabel;
    }

    public String getNoidungInvalid() {
        noidungInvalid = Utils.getResource("NOI_DUNG_INVALID");
        return noidungInvalid;
    }

    public String getDoimaLabel() {
        doimaLabel = Utils.getResource("DOI_MA_KHAC");
        return doimaLabel;
    }

    public String getGuiLabel() {
        guiLabel = Utils.getResource("GUI");
        return guiLabel;
    }

    public String getPhoneInvalid() {
        phoneInvalid = Utils.getResource("PHONE_INVALID");
        return phoneInvalid;
    }

    public String getDiachiLabel() {
        diachiLabel = Utils.getResource("DIA_CHI_LABEL");
        return diachiLabel;
    }

    public String getPhoneLabel() {
        phoneLabel = Utils.getResource("PHONE_LABEL");
        return phoneLabel;
    }
}
